package com.mall.web.util;

import java.io.File;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class FileTest {

	public static void main(String[] args) throws Exception {
		getFileName("//192.168.31.214/ps前期/PS全套抠图视频教程");
	}
	
	
	
	

	public static void getFileName(String path) throws Exception{
		File f = new File(path);
		if (!f.exists()) {
			System.out.println(path + " not exists");
			return;
		}

		File fa[] = f.listFiles();
		for (int i = 0; i < fa.length; i++) {
			File fs = fa[i];
			if (fs.isDirectory()) {
				System.out.println(fs.getName() + " [目录]");
				getFileName(fs.getPath());
			} else {
				String fileNamewenjian = fs.getName();
				if(fileNamewenjian.endsWith(".swf") || fileNamewenjian.endsWith(".mp4")){
					
				
				String pyNamewenjian = getPingYin(fileNamewenjian); 
				
				String fileName = fs.getName().replaceAll("[.][^.]+$", "");
				//System.out.println("原名："+fileName);
				String pyName = getPingYin(fileName); 
				// 创建格式化对象
			//	System.out.println(pyName.replace(",",""));
				//System.out.println(fs.getPath()+"..........");
				fs.renameTo(new File(path + "/" + pyNamewenjian.replace(",","")));
				
				String url = "3psktship/"+pyNamewenjian.replace(",","");
				
				/*插入数据库*/
				Connection conn = null;
				String dbUrl = "jdbc:mysql://192.168.31.187:3306/mall?"
						+ "user=root&password=123456&useUnicode=true&characterEncoding=UTF8";
				Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
				conn = (Connection) DriverManager.getConnection(dbUrl);
				Statement stmt = (Statement) conn.createStatement();
				
				String code = "mn3qy1";
				Integer zhangjie = i+1;
				String sql = "insert into ps_video(zhangjie,title,url,category,code,ps_item_id,gmt_create,gmt_modify,status,type) " + " "
								+ "values ('"+zhangjie+"','"+ fileName + "','" + url + "','" + 3+"','"+code+ "','"+3+"',now(),now(),0,0)";
				// System.out.println(sql);
				stmt.executeUpdate(sql);
				
				}
				
				
				
				
				
				
			}
		}
	}

	
	
	
	
	/**
	 * 将字符串中的中文转化为拼音,英文字符不变
	 * 
	 * @param inputString
	 *            汉字
	 * @return
	 */
	public static String getPingYin(String inputString) {
		StringBuffer pinyinName = new StringBuffer();  
        char[] nameChar = inputString.toCharArray();  
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
        for (int i = 0; i < nameChar.length; i++) {  
            if (nameChar[i] > 128) {  
                try {  
                    // 取得当前汉字的所有全拼  
                    String[] strs = PinyinHelper.toHanyuPinyinStringArray(  
                            nameChar[i], defaultFormat);  
                    if (strs != null) {  
                        for (int j = 0; j < strs.length; j++) {  
                            pinyinName.append(strs[j]);  
                            if (j != strs.length - 1) {  
                                pinyinName.append(",");  
                            }  
                        }  
                    }  
                } catch (BadHanyuPinyinOutputFormatCombination e) {  
                    e.printStackTrace();  
                }  
            } else {  
                pinyinName.append(nameChar[i]);  
            }  
            pinyinName.append(" ");  
        }  
        // return pinyinName.toString();  
        return parseTheChineseByObject(discountTheChinese(pinyinName.toString())); 
	}
	
	 /** 
     * 去除多音字重复数据 
     *  
     * @param theStr 
     * @return 
     */  
    private static List<Map<String, Integer>> discountTheChinese(String theStr) {  
        // 去除重复拼音后的拼音列表  
        List<Map<String, Integer>> mapList = new ArrayList<Map<String, Integer>>();  
        // 用于处理每个字的多音字，去掉重复  
        Map<String, Integer> onlyOne = null;  
        String[] firsts = theStr.split(" ");  
        // 读出每个汉字的拼音  
        for (String str : firsts) {  
            onlyOne = new Hashtable<String, Integer>();  
            String[] china = str.split(",");  
            // 多音字处理  
            for (String s : china) {  
                Integer count = onlyOne.get(s);  
                if (count == null) {  
                    onlyOne.put(s, new Integer(1));  
                } else {  
                    onlyOne.remove(s);  
                    count++;  
                    onlyOne.put(s, count);  
                }  
            }  
            mapList.add(onlyOne);  
        }  
        return mapList;  
    }  

    /** 
     * 解析并组合拼音，对象合并方案
     *  
     * @return 
     */  
    private static String parseTheChineseByObject(  
         List<Map<String, Integer>> list) {  
        Map<String, Integer> first = null; // 用于统计每一次,集合组合数据  
        // 遍历每一组集合  
        for (int i = 0; i < list.size(); i++) {  
            // 每一组集合与上一次组合的Map  
            Map<String, Integer> temp = new Hashtable<String, Integer>();  
            // 第一次循环，first为空  
            if (first != null) {  
                // 取出上次组合与此次集合的字符，并保存  
                for (String s : first.keySet()) {  
                    for (String s1 : list.get(i).keySet()) {  
                        String str = s + s1;  
                        temp.put(str, 1);  
                    }  
                }  
                // 清理上一次组合数据  
                if (temp != null && temp.size() > 0) {  
                    first.clear();  
                }  
            } else {  
                for (String s : list.get(i).keySet()) {  
                    String str = s;  
                    temp.put(str, 1);  
                }  
            }  
            // 保存组合数据以便下次循环使用  
            if (temp != null && temp.size() > 0) {  
                first = temp;  
            }  
        }  
        String returnStr = "";  
        if (first != null) {  
            // 遍历取出组合字符串  
            for (String str : first.keySet()) {  
                returnStr += (str + ",");  
            }  
        }  
        if (returnStr.length() > 0) {  
            returnStr = returnStr.substring(0, returnStr.length() - 1);  
        }  
        return returnStr;  
    }


}

